package com.sky.service.impl;


import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.mapper.UserMapper;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Morpeko
 * @description 针对表【user(用户信息)】的数据库操作Service实现
 * @createDate 2024-08-13 21:33:08
 */
@Service
public class UserServiceImpl implements UserService {
    //获取openid的微信服务器接口
    public static final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户微信登入和注册接口
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO loginAndRegister(UserLoginDTO userLoginDTO) {
        //1.根据前端小程序传递的临时授权码code, 获取微信用户的openid(用户唯一标识)
        String openid = getOpenid(userLoginDTO.getCode());
        //2.如果前端没有传递授权码/授权码无效, 则返回错误信息
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.查看数据库中是否有该openid的用户, 如果有, 则直接登录, 如果没有, 则注册
        //查看数据库中是否有该openid的用户
        User user = userMapper.login(openid);
        if (user == null) {
            //注册该用户

            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.registerUser(user);


        }
        //4.如果数据库中有该openid的用户, 则登入成功,组装UserLoginVO对象返回前端
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setOpenid(openid);
        userLoginVO.setId(user.getId());


        //业务实现: 调用UserMapper的loginAndRegister方法, 实现用户微信登入和注册功能
        return userLoginVO;
    }

    private String getOpenid(String code) {
        //构建请求参数的Map集合
        Map<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        //传入包含请求参数的Map集合, 和请求的url, 发送请求, 获取微信服务器返回的openid和session_key
        String result = HttpClientUtil.doGet(WECHAT_LOGIN_URL, params);
        JSONObject jsonObject = JSONObject.parseObject(result);//解析json字符串为json对象
        String openid = jsonObject.getString("openid");
        //返回openid
        return openid ;
    }
}




